/*
 * L'application ZenContact en Grails a été écrite par Nicolas Martignole,
 * elle est mise à disposition selon les termes de la licence
 *
 * Creative Commons Paternité-Pas d'Utilisation Commerciale-Partage des Conditions Initiales à l'Identique 2.0 France.
 * 
 * Basé(e) sur une oeuvre http://www.touilleur-express.fr/2009/12/20/grails-lapplication-zencontact-de-zenika/
 *
 * Les autorisations au-delà du champ de cette licence peuvent être obtenues à http://touilleur-express.fr/.
 * Voir http://creativecommons.org/licenses/by-nc-sa/2.0/fr/
 *
 * Copyright(c) Nicolas Martignole 2010.
 *
 */
package org.letouilleur.demo

import grails.converters.XML
import grails.converters.JSON

class ContactController {

  static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

  def index = {
    redirect(uri: '/')
  }

  def list = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
    // Il faut passer en argument l'objet params afin que les proprietes offset et max
    // soient utilisees pour restreindre la selection et creer la pagination
    [contactInstanceList: Contact.listOrderByNom(params), contactInstanceTotal: Contact.count(), contactInstance: new Contact()]
  }

  def create = {
    def contactInstance = new Contact()
    contactInstance.properties = params
    return [contactInstance: contactInstance]
  }

  def save = {
    def contactInstance = new Contact(params)
    if (contactInstance.save(flush: true)) {
      flash.message =  contactInstance.prenom + " " + contactInstance.nom + " enregistré !"
      redirect(action: "show", id: contactInstance.id)
    }
    else {
      render(view: "create", model: [contactInstance: contactInstance])
    }
  }

  def show = {
    def contactInstance = Contact.get(params.id)
    if (!contactInstance) {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
    else {
      [contactInstance: contactInstance]
    }
  }

  def edit = {
    def contactInstance = Contact.get(params.id)
    if (!contactInstance) {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
    else {
      return [contactInstance: contactInstance]
    }
  }

  def update = {
    def contactInstance = Contact.get(params.id)
    if (contactInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (contactInstance.version > version) {

          contactInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'contact.label', default: 'Contact')] as Object[], "Another user has updated this Contact while you were editing")
          render(view: "edit", model: [contactInstance: contactInstance])
          return
        }
      }
      contactInstance.properties = params
      if (!contactInstance.hasErrors() && contactInstance.save(flush: true)) {
        flash.message = "${message(code: 'default.updated.message', args: [message(code: 'contact.label', default: 'Contact'), contactInstance.id])}"
        redirect(action: "show", id: contactInstance.id)
      }
      else {
        render(view: "edit", model: [contactInstance: contactInstance])
      }
    }
    else {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
  }

  def delete = {
    def contactInstance = Contact.get(params.id)
    if (contactInstance) {
      try {
        contactInstance.delete(flush: true)
        flash.message = params.id + " effacé avec succès"
        redirect(action: "list")
      }
      catch (org.springframework.dao.DataIntegrityViolationException e) {
        flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
        redirect(action: "show", id: params.id)
      }
    }
    else {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
  }

  def listAsXml = {
    def newList = Contact.listOrderByNom()
    render newList as XML
  }

  def listAsJson = {
    def newList = Contact.listOrderByNom()
    render newList as JSON
  }

  def showAsXml = {
    def contactInstance = Contact.get(params.id)
    if (!contactInstance) {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
    else {
      render contactInstance as XML
    }
  }

  def inlineEdit = {
    def contactInstance = Contact.get(params.id)
    if (!contactInstance) {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'contact.label', default: 'Contact'), params.id])}"
      redirect(action: "list")
    }
    else {
      contactInstance.nom = params.nom
      contactInstance.save()
      return [contactInstance: contactInstance]
    }
  }

  def saveQuickInput = {
    params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)

    def contactInstance = new Contact(params)

    def existingUser = Contact.findByNomAndPrenom(params.nom, params.prenom)
    if (!existingUser) {

      contactInstance.save(flush: true)
      flash.message = "Utilisateur enregistré"
      [contactInstanceList: Contact.listOrderByNom(params), user: contactInstance, contactInstanceTotal: Contact.count()]
    } else {
      [contactInstanceList: Contact.list(params), user: contactInstance, contactInstanceTotal: Contact.count(), erreur: "Cet utilisateur existe déjà"]
    }
  }
}
